package pl.maciejziarko.mshare.web.mvc.aspect;

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.ui.Model;
import pl.maciejziarko.mshare.service.AccountService;
import pl.maciejziarko.mshare.service.ResourceService;
import pl.maciejziarko.mshare.service.exception.AccountServiceException;
import pl.maciejziarko.mshare.service.exception.ResourceServiceException;

/**
 * @author Maciej Ziarko
 */
@Component
@Aspect
public class StatsAspect {

    private static final Logger LOG = LoggerFactory.getLogger(StatsAspect.class);

    private AccountService accountService;
    private ResourceService resourceService;

    @Autowired
    public StatsAspect(AccountService accountService, ResourceService resourceService) {
        this.accountService = accountService;
        this.resourceService = resourceService;
    }

    @Pointcut("execution(* pl.maciejziarko.mshare.web.mvc.*Controller.*(org.springframework.ui.Model, ..)) && args(model, ..)")
    public void pointcut(Model model) {
    }

    @Before("pointcut(model)")
    public void addStats(Model model) {
        //TODO REFACTOR
        long accountsCount;
        long resourcesCount;
        try {
            accountsCount = accountService.countAccounts();
        } catch (AccountServiceException e) {
            accountsCount = 0;
        }
        try {
            resourcesCount = resourceService.countResources();
        } catch (ResourceServiceException e) {
            resourcesCount = 0;
        }
        model.addAttribute("accountsCount", accountsCount);
        model.addAttribute("resourcesCount", resourcesCount);
    }

}
